import {messages} from "share/common";
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import moment from 'moment'
import { Modal, Icon, Popover } from 'antd'
import Ellipsis from "ant-design-pro/lib/Ellipsis"
import Condition from 'components/condition'
import ColumnLayout from 'components/template/slide-document/column-layout'
import BaseRequestDetail from 'containers/request/entrance/request-detail'
import ContractDetail from 'containers/contract/my-contract/contract-detail'
import 'styles/financial-management/new-finance-audit/components/related-bills.scss'

const { If } = Condition;

const { ColumnLayoutLeft, ColumnLayoutRight } = ColumnLayout;

class RelatedBills extends Component {

  state = {
    entityType: this.props.entityType,
    entityOID: this.props.entityOID,
    viewedList: [],
  };

  componentDidMount() {
    let viewedList = this.props.viewedList;
    viewedList.addIfNotExist(this.props.entityOID);
    this.setState({ viewedList });
    if (window.addEventListener) {
      window.addEventListener('keyup', this.handleKeyUp);
    } else {
      window.attachEvent('onkeyup', this.handleKeyUp);
    }
  }

  componentWillUnmount() {
    if (window.addEventListener) {
      window.removeEventListener('keyup', this.handleKeyUp);
    } else {
      window.detachEvent('onkeyup', this.handleKeyUp);
    }
  }

  //键盘事件
  handleKeyUp = e => {
    e.stopPropagation();
    const { visible, info } = this.props;
    const { entityOID } = this.state;
    const { expenseReportApplicationDTOS = [], contractHeaderOID } = info;
    let list = [];
    expenseReportApplicationDTOS.map(item => list.push(item.applicationOID));
    contractHeaderOID && list.push(contractHeaderOID);
    let currentIndex = list.indexOf(entityOID);
    if (visible) {
      switch (e.keyCode) {
        // UP
        case 38:
          if (currentIndex > 0) {
            this.handleClick(1001, list[currentIndex - 1]);
          }
          break;
        // DOWN
        case 40:
          if (currentIndex < list.length - 1) {
            let nextOID = list[currentIndex + 1];
            this.handleClick(nextOID === contractHeaderOID ? 6001 : 1001, nextOID);
          }
          break;
      }
    }
  };

  handleClick = (entityType, entityOID) => {
    let { viewedList } = this.state;
    viewedList.addIfNotExist(entityOID);
    // 处理统一类型的单据切换不刷新页面的情况
    this.setState({ entityType: '' }, () => {
      this.setState({ entityType, entityOID, viewedList });
    });
  };

  renderLeftContent = () => {
    const { info } = this.props;
    const { entityType, entityOID, viewedList } = this.state;
    const { expenseReportApplicationDTOS = [], contractHeaderId, contractNumber } = info;
    return (
      <div className="related-bills-list">
        <If value={expenseReportApplicationDTOS.length}>
          <div className="related-bills-list-title">
            {messages('expense-14.key203')/*关联申请*/}（{expenseReportApplicationDTOS.length}）
          </div>
          {expenseReportApplicationDTOS.map(item => (
            <div
              className={this.classNames([
                'related-bills-list-item', {
                'selected': entityOID === item.applicationOID,
                'viewed':  entityOID !== item.applicationOID && viewedList.includes(item.applicationOID)
              }])}
              onClick={() => this.handleClick(1001, item.applicationOID)}
            >
              <Popover content={item.applicationBusinessCode}>
                <Ellipsis lines={1}>{item.applicationBusinessCode}</Ellipsis>
              </Popover>
              <If value={item.travelStartDate && item.travelEndDate}>
                <div style={{ marginTop: 6, fontSize: 12 }}>
                  {moment(item.travelStartDate).format('YYYY-MM-DD')}
                  &nbsp;~&nbsp;
                  {moment(item.travelEndDate).format('YYYY-MM-DD')}
                </div>
              </If>
            </div>
          ))}
        </If>
        <If value={contractHeaderId}>
          <div className="related-bills-list-title">
            {messages('expense-14.key204')/*关联合同*/}（1）
          </div>
          <div
            className={this.classNames([
              'related-bills-list-item', {
              'selected': entityType === 6001,
              'viewed':  entityType !== 6001 && viewedList.includes(info.contractHeaderOID)
            }])}
            onClick={() => this.handleClick(6001, info.contractHeaderOID)}
          >
            <Popover content={contractNumber}>
              <Ellipsis lines={1}>{contractNumber}</Ellipsis>
            </Popover>
          </div>
        </If>
      </div>
    )
  };

  renderRightContent = () => {
    const { info: { expenseReportApplicationDTOS, contractHeaderId, applicantOID }, corporateFlag } = this.props;
    const { entityType, entityOID } = this.state;
    if (entityType === 1001) {
      let application = expenseReportApplicationDTOS.filter(item => item.applicationOID === entityOID)[0] || {};
      const { applicationFormOID, applicationOID } = application;
      return (
        <div style={{ padding: 20 }}>
          <BaseRequestDetail
            _isSlideFrame
            params={{
              readOnly: true,
              applicationOID,
              formOID: applicationFormOID,
              entry: 'financeView',
              erApplicantOID: applicantOID
            }}
          />
        </div>
      )
    } else if (entityType === 6001) {
      return (
        <ContractDetail
          params={{
            readOnly: true,
            id: contractHeaderId,
            entityOID,
            entry: 'audit'
          }}
        />
      )
    } else {
      return null;
    }
  };

  handleClose = () => {
    const { viewedList } = this.state;
    this.props.afterClose(viewedList);
    this.props.onClose();
  };

  render() {
    const { visible, leftWidth } = this.props;
    return (
      <Modal
        visible={visible}
        title={(
          <div className="font-default">
            <Icon type='left' className="related-bills-tip-icon" onClick={this.handleClose} />
            {messages('expense-14.key205')/*查看关联单据*/}
            <span className="related-bills-tip">{messages('expense-14.key206')/*多个单据时，键盘上下可以切换单据*/}</span>
          </div>
        )}
        className="related-bills"
        width='100%'
        footer={null}
      >
        <ColumnLayout leftWidth={leftWidth}>
          <ColumnLayoutLeft>{this.renderLeftContent()}</ColumnLayoutLeft>
          <ColumnLayoutRight>{this.renderRightContent()}</ColumnLayoutRight>
        </ColumnLayout>
      </Modal>
    )
  }
}

RelatedBills.open = function (config = {}, env) {
  let defaultConfig = {
    visible: false,
    leftWidth: 200,
    onClose: close
  };
  let targetConfig = Object.assign(
    {},
    defaultConfig,
    config,
  );
  let div = document.createElement('div');
  let container = document.body;
  container.appendChild(div);
  function render(props) {
    if (env) {
      ReactDOM.unstable_renderSubtreeIntoContainer(env, <RelatedBills {...props}/>, div)
    } else {
      ReactDOM.render(<RelatedBills {...props}/>, div)
    }
  }
  function close() {
    if (div) {
      ReactDOM.unmountComponentAtNode(div);
      container.removeChild(div);
      div = null;
    }
  }
  render(targetConfig);
};

export default RelatedBills;
